import type { Directive } from 'vue';

const updateTitle = (el:Element) => {
  const containerHeight = el.clientHeight;
  const containerWidth = el.clientWidth;

  // 创建一个临时元素
  const tempElement = document.createElement('span');
  tempElement.style.visibility = 'hidden';
  tempElement.style.position = 'absolute';
  tempElement.style.whiteSpace = 'wrap';
  tempElement.style.wordBreak = 'break-all';

  const style = window.getComputedStyle(el);
  tempElement.style.width = containerWidth + 'px';
  tempElement.style.fontSize = style.fontSize;
  tempElement.style.fontFamily = style.fontFamily;
  tempElement.style.lineHeight = style.lineHeight;
  tempElement.style.letterSpacing = style.letterSpacing;

  tempElement.textContent = el.textContent;

  // 将临时元素添加到文档中
  document.body.appendChild(tempElement);
  const textHeight = tempElement.clientHeight;

  // 移除临时元素
  document.body.removeChild(tempElement);
  if (textHeight > containerHeight) {
    el.setAttribute('title', el.textContent + '');
  } else {
    el.removeAttribute('title');
  }
};

export default {
  mounted(el) {
    el.addEventListener('mouseenter', () => {
      updateTitle(el);
    });
  },
  updated(el) {
    setTimeout(() => updateTitle(el), 500);
  }
} as Directive;
